1. 题目描述(中等难度)
[warning] 47. 全排列 II
2. 解法一:回溯
class Solution {
List<List<Integer>> resp = new ArrayList<>();
List<Integer> ans = new ArrayList<>();
public List<List<Integer>> permuteUnique(int[] nums) {
if(nums == null || nums.length == 0){
return resp;
}
boolean[] used = new boolean[nums.length];
backTracking(nums,used);
return resp;
}
public void backTracking(int[] nums,boolean[] used){
if(ans.size() == nums.length && !resp.contains(ans)){
resp.add(new ArrayList<>(ans));
return;
}
for(int i=0;i<nums.length;i++){
if(used[i] == true){
continue;
}
used[i] = true;
ans.add(nums[i]);
backTracking(nums,used);
ans.remove(ans.size()-1);
used[i] = false;
}
}
}
上述代码优化 排序后去重
class Solution {
List<List<Integer>> resp = new ArrayList<>();
List<Integer> ans = new ArrayList<>();
public List<List<Integer>> permuteUnique(int[] nums) {
if(nums == null || nums.length == 0){
return resp;
}
Arrays.sort(nums);
boolean[] used = new boolean[nums.length];
backTracking(nums,used);
return resp;
}
public void backTracking(int[] nums,boolean[] used){
if(ans.size() == nums.length){
resp.add(new ArrayList<>(ans));
return;
}
for(int i=0;i<nums.length;i++){
if (used[i] || (i > 0 && nums[i] == nums[i - 1] && !used[i - 1])) {
continue;
}
used[i] = true;
ans.add(nums[i]);
backTracking(nums,used);
ans.remove(ans.size()-1);
used[i] = false;
}
}
}
或者
class Solution {
List<List<Integer>> resp = new ArrayList<>();
List<Integer> ans = new ArrayList<>();
public List<List<Integer>> permuteUnique(int[] nums) {
if(nums == null || nums.length == 0){
return resp;
}
Arrays.sort(nums);
boolean[] used = new boolean[nums.length];
backTracking(nums,used);
return resp;
}
public void backTracking(int[] nums,boolean[] used){
if(ans.size() == nums.length){
resp.add(new ArrayList<>(ans));
return;
}
for(int i=0;i<nums.length;i++){
if(used[i] == true || (i>0 && nums[i] == nums[i-1] && used[i-1] == false)){
continue;
}
used[i] = true;
ans.add(nums[i]);
backTracking(nums,used);
ans.remove(ans.size()-1);
used[i] = false;
}
}
}
注意,需要先对数组进行排序处理。 排序去重。